#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int random()
{
     int i = 1 + rand()%10;

     if(i <= 8)
     {
         return 2;
     }
     else
     {
         return 4;
     }
}

void show(int *pi)
{
    int x, y;

    for(y = 1; y<= 4; y++)
    {
        for(x = 1; x<= 4; x++)
        {
            printf("%d ",*(pi + y * 6 + x));
        }
        printf("\n");
    }
}

void create(int *pi)
{
    int x, y;

    x = 1 + rand()%4;

    y = 1 + rand()%4;

    while(*(pi + y * 6 + x) != 0)
    {
        x = 1 + rand()%4;

        y = 1 + rand()%4;
    }
    *(pi + y * 6 + x) = random();
}

void move(int *pi, int x, int y, int i, int j)
{
    //只做了一行或一列的
    int array[5] = {0};

    int k, temp = 0, xi, yi;

    xi = x;

    yi = y;

    for(k = 0; k < 4; k++)
    {
        if(*(pi + yi * 6 + xi) != 0)
        {
            temp++;
        }
        xi = xi + i;

        yi = yi + j;
    }

    xi = x;

    yi = y;

    for(k = 0; k < temp; )
    {
        //*(pi + y * 6 + x)
        if(*(pi + yi * 6 + xi) != 0)
        {
            array[k] = *(pi + yi * 6 + xi);

            k++;

            *(pi + yi * 6 + xi) = 0;
        }
        xi = xi + i;

        yi = yi + j;
    }
    //temp = k;

    for(k = 0; k < 4; k++)
    {
        if(array[k] == array[k + 1])
        {
            array[k] = array[k] + array[k + 1];

            array[k + 1] = 0;
        }
        //printf("%d ",array[k]);
    }

    //printf("\n");

    for(k = 0; k < 4; k++)
    {
        if(array[k] != 0)
        {
            *(pi + y * 6 + x) = array[k];

            x = x + i;

            y = y + j;
        }
    }
}

void moveall(int *pi)
{
    int i;

    int x,y;

    //2468控制方向
    printf("请输入你想移动的方向：");

    scanf("%d",&i);

    //向下移
    if(i == 2)
    {
        for(x = 1; x <= 4; x++)
        {
            move(pi, x, 4, 0, -1);
        }
    }

    //向上移
    if(i == 8)
    {
        for(x = 1; x<= 4; x++)
        {
            move(pi, x, 1, 0, 1);
        }
    }

    //向左移
    if(i == 4)
    {
        for(y = 1; y<= 4; y++)
        {
            move(pi, 1, y, 1, 0);
        }
    }

    //向右移
    if(i == 6)
    {
        for(y = 1; y <= 4; y++)
        {
            move(pi, 4, y, -1, 0);
        }
    }
}

int main()
{
    int i, j;

    int array[6][6] = {0};

    srand(time(0));

    create(array);

    while(1)
    {
        create(array);

        show(array);

        printf("\n");

        moveall(array);
    }

    return 0;















}
